package org.example.service;


import org.example.entity.Order;
import org.example.entity.User;
import org.example.mapper.OrderMaper;
import org.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

@Service
public class TransService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMaper orderMapper;

    @Transactional
    public String trans(User user, Order order) {
        boolean isTransactionActive = TransactionSynchronizationManager.isActualTransactionActive();
        System.out.println("事务是否激活：" + isTransactionActive);
        userMapper.insert(user);
        orderMapper.insert(order);
        return "success";
    }

    @Transactional(rollbackFor = Exception.class,propagation= Propagation.REQUIRES_NEW)
    public String transition() {
        User user = new User();
        user.setName("John");
        user.setAge(25);

        Order order = new Order();
        order.setUserId("1");
        order.setItemId(1);
        order.setItemNum(100);

        trans(user, order);
        return "ok";
    }
}
